<template>
  <div class="audio-div">
    <audio
      id="audio"
      :src="adsrc"
      :autoplay='isAutoplay'
      controls
      @error="audioError($event)"
      @ended="onEnded($event)"
      @timeupdate="timeup($event)"
      @play="onPlay($event)"
    ></audio>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { session, ranDomRange } from '@/common/utils'
export default {
  name: 'AudioComponents',
  data() {
    return {
      adsrc: 'http://localhost:3000/shuoshuren.mp3',
      isAutoplay: false,
    }
  },
  watch: {
    '$store.state.audioId'(newValue, oldValue) {
      this.getUrl(newValue.id)
    },
  },
  mounted() {
    // 把Audio实例挂载到window上
    window.audioElement = document.querySelector('#audio')
  },
  methods: {
    ...mapMutations(['getAudioDate', 'getTotaTime', 'getAudioobj']),
    // 修改开始默认音乐
    async StartBgm() {
      /***
       * 后面后台系统搞了  搞开始默认音乐在后台修改
       */
      // try {
      //   const request = await this.$http.host.get('/StartBgm')
      // } catch (err) {
      //   console.info(err)
      //   // 错误的默认音乐  说书人
      //   this.adsrc = 'http://localhost:3000/shuoshuren.mp3'
      // }
    },
    // 获取音乐地址
    async getUrl(id) {
      const request = await this.$http.music.get('/song/url', { id, br: 999000 })
      this.adsrc = request.data[0].url
      this.isAutoplay = true
    },
    // 播放错误
    audioError(e) {
      if (this.isAutoplay) {
        this.$message({
          message: '音乐播放错误,正在切换下一首',
          type: 'error',
        })
        this.getXia()
      } else {
        console.error('音乐播放错误', e)
        this.$message({
          message: '默认歌曲错误？？？',
          type: 'error',
        })
      }
    },
    // 音乐播放结束
    onEnded(e) {
      // 用户清空了播放列表就不切换了
      if (!this.$store.state.isSongsNull) return
      this.$message({
        message: '正在切换下一首',
        type: 'success',
      })
      const audioplayMode = this.$store.state.audioplayMode
      switch (audioplayMode) {
        case 1:
          this.Randomplay()
          break
        case 2:
          //重新加载音频/视频元素
          window.audioElement.load()
          setTimeout(() => {
            window.audioElement.play()
          }, 300)
          break
        default:
          this.getXia()
      }
    },
    // 播放时间
    timeup(e) {
      // duration 总时长 currentTime 已经播放的时间
      const { duration, currentTime } = e.target
      const date = {
        curren: this.second(currentTime),
        left: ((currentTime / duration) * 100).toFixed(2),
      }
      this.getAudioDate(date)
    },
    //音乐总时长
    onPlay(e) {
      const duration = e.target.duration
      const derDate = this.second(duration)
      this.getTotaTime(derDate)
    },
    // 秒数转换为分秒
    second(value) {
      // 分
      let fen = Math.floor(value / 60)
      // 秒
      let miao = Math.floor(value % 60)
      miao = miao >= 10 ? miao : '0' + miao
      // if(fen == NaN || miao == '0NaN'){
      //   fen = '0:'
      //   miao = '00'
      // }
      return `${fen}:${miao}`
    },
    // 切换下一首
    getXia() {
      // 获取歌单
      const songs = session.get('songs')
      // 判断当前歌曲是不是歌单中的最后一首
      let obj = this.$store.state.audioIndex === songs.length ? songs[0] : songs[this.$store.state.audioIndex + 1]
      // this.$store.commit('getAudioobj', obj)
      this.getAudioobj(obj)
    },
    // 随机播放
    Randomplay() {
      // 获取歌单
      const songs = session.get('songs')
      // 随机数
      let a = ranDomRange(0, songs.length)
      let audioIndex = this.$store.state.audioIndex
      if (a == audioIndex) {
        this.Randomplay()
      }
      // this.$store.commit('getAudioobj', songs[a])
      this.getAudioobj(obj)
    },
  },
}
</script>

<style lang="scss" scoped>
.audio-div {
  position: fixed;
  /* bottom: 14vh; */
  top: 94vh;
  left: 0vw;
  z-index: 9999;
}
</style>